import { LOGIN_TOKEN } from '@/global/constants'
import { loaclCache } from '@/utils/cache'
import { firstMenu } from '@/utils/mapMenus'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/login',
      component: () => import('../views/login/Login.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('../views/main/main.vue')
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('../views/not-found/NotFound.vue')
    }
  ]
})

// 导航守卫
// 参数：to 表示跳转的位置  from表示哪跳转来的位置
// 返回值表示决定调转的路径
router.beforeEach((to) => {
  const token = loaclCache.getCache(LOGIN_TOKEN)
  // startsWith用于检查字符串是否以指定的前缀开头
  if (to.path.startsWith('/main') && !token) {
    return '/login'
  }
  // 进入main页面
  if (to.path === '/main') {
    return firstMenu?.url
  }
})

export default router
